import { Select, Form, Input, Modal, message } from 'antd';
import { useEffect, useState } from 'react';
import axios from 'axios';

const CollectionCreateForm = ({ open, onSubmit, onCancel, roleList, regionList }) => {
  const [form] = Form.useForm();
  const { Option } = Select;
  return (
    <Modal
      destroyOnClose={true}
      open={open}
      title="创建用户"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onSubmit(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"

      >
        <Form.Item
          name="username"
          label="用户姓名"
          rules={[
            {
              required: true,
              message: '请输入用户姓名！',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            {
              required: true,
              message: '请输入用户密码！',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="sex"
          label="性别"
          rules={[
            {
              required: true,
              message: '请输入用户性别！',
            },
          ]}>
          <Select >
            <Option value="male">男</Option>
            <Option value="female">女</Option>
            <Option value="unknown">保密</Option>
          </Select>

        </Form.Item>

        <Form.Item
          name="roleId"
          label="角色"
          rules={[
            {
              required: true,
              message: '请选择用户角色！',
            },
          ]}>

          <Select options={roleList} />
        </Form.Item>


        <Form.Item
          name="region"
          label="区域"
          rules={[
            {
              required: true,
              message: '请选择用户区域！',
            },
          ]}
        >
          <Select options={regionList} />
        </Form.Item>

      </Form>
    </Modal>
  );
};

const CreateUser = (props) => {

  const [roleList, setRoleList] = useState([])
  const [regionList, setRegionList] = useState([])
  useEffect(() => {
    axios.get("http://192.168.2.3:3000/roles")
      .then(res => {
        const newList = res.data.map(({ id, roleName }) => ({ label: roleName, value: id }));
        setRoleList(newList)
      })
    return () => { }
  }, [])
  useEffect(() => {
    axios.get("http://192.168.2.3:3000/regions")
      .then(res => {
        const newList = res.data.map(({ value, title }) => ({ label: title, value: value }));
        setRegionList(newList)
      })
    return () => { }
  }, [])

  const onSubmit = (values) => {
    props.setCreateOpen(false);
    props.setLoading(true)
    onCreateAndGet(values)

  }

  async function onCreateAndGet(values) {
    values.status=true;
    console.log('Received values of form: ', values);
    //同步保存数据然后更新列表
    await axios.post(`http://192.168.2.3:3000/users`, values)
      .then(
        response => {
          console.log(response)
          if (response.status === 201) {
            message.success('保存成功');

            //异步获取新的角色数据
          } else {
            message.error('保存失败');
          }
        })
      .catch(error => {
        message.error('保存失败');
      });
    const get = await axios.get("http://192.168.2.3:3000/users?_expand=role");
    const getRes = get.data;
    console.log("getRes", getRes)
    props.setList(getRes)
    props.setLoading(false)


  };

  return (
    <div>
      <CollectionCreateForm
        roleList={roleList}
        regionList={regionList}
        open={props.createOpen}
        onSubmit={onSubmit}
        onCancel={() => {
          props.setCreateOpen(false);
        }}
      />
    </div>
  );
}



export default CreateUser;